package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.util.List;

import org.apache.http.client.methods.HttpGet;
import org.jsoup.nodes.Element;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.sub.impl20140402.v3.travelsky.TravelskyInlandOneWayAdapter;
import com.foreveross.crawl.adapter.sub.impl20140402.v3.travelsky.TravelskyInlandRoundAdapter;
import com.foreveross.crawl.common.exception.self.UnableParseRouteTypeException;
import com.foreveross.crawl.common.util.ImageUtils;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.common.collect.ImmutableList;

/**
 * 奥凯航空适配器 http://bk.travelsky.com/bkair/index.jsp <br/>
 * 价格、航班号，航班时间需要解析图片。
 * 
 * @author mingliangluo重写于2014-08-05 .
 * @date 2014-05-22
 * @version 1.0v
 */
@SuppressWarnings({ "deprecation", "unchecked" })
public class TravelskyAdapter extends AbstractAdapter {

	/** ******************************** Constructor *********************************************** */

	public TravelskyAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}

	/** ******************************** Params *********************************************** */

	protected String requestId = null; // 请求编号
	protected ImageUtils imageUtils = new ImageUtils(); // 图片解析工具类
	protected HtmlPage queryPage = null;
	protected final static List<String> cabinNames = ImmutableList.of("头等舱", "优享头等舱", "提前销售", "最低票价");

	/** ******************************** FACTORY *********************************************** */

	private TravelskyInlandRoundAdapter roundAdapter = null;
	private TravelskyInlandOneWayAdapter onewayAdapter = null;

	private TravelskyInlandRoundAdapter getInlandRoundAdapter() {
		if (roundAdapter == null) roundAdapter = new TravelskyInlandRoundAdapter(taskQueue);
		return roundAdapter;
	}

	private TravelskyInlandOneWayAdapter getInlandOneWayAdapter() {
		if (onewayAdapter == null) onewayAdapter = new TravelskyInlandOneWayAdapter(this,taskQueue);
		return onewayAdapter;
	}

	/** ******************************** Override *********************************************** */

	@Override
	public Object fetch(String url) throws Exception {
		switch (super.getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			return getInlandOneWayAdapter().fetch();
		case DOMESTIC_ROUNDTRIP:
			return getInlandRoundAdapter().fetch();
		default:
			throw new UnableParseRouteTypeException(taskQueue, getRouteType().getName());
		}
	}

	@Override
	public List<Object> paraseToVo(Object obj) throws Exception {
		switch (super.getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			return (List<Object>) getInlandOneWayAdapter().parse(obj);
		case DOMESTIC_ROUNDTRIP:
			return (List<Object>) getInlandRoundAdapter().parse(obj);
		default:
			throw new UnableParseRouteTypeException(taskQueue, getRouteType().getName());
		}
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		System.out.println("父类的验证 。");
		if (fetchObject == null) {
			throw new Exception("抓取到的数据为空！");
		}
		if (RegHtmlUtil.regMathcher(fetchObject.toString(), "公共的出错页面")) {
			throw new Exception("服务器忙，请稍后再试 ");
		}
		return true;
	}

	@Override
	public String getUrl() throws Exception {
		return null;
	}

	/** ******************************** Fetch *********************************************** */

	/**
	 * 获取ReauestId。
	 * 
	 * @return
	 * @throws Exception
	 */
	public String setCookie() throws Exception {
		String page = null;
		try {
			page = super.excuteRequest(new HttpGet("http://bk.travelsky.com/bkair/index.jsp"));
			requestId = RegHtmlUtil.regStr(page, "name=\"queryFlightRequestId\"\\s*?value=\"(.*?)\""); // 设置一下RequestID
			super.setLenghtCount(page.getBytes().length);
		} catch (Exception e) {
			logger.error(String.format("设置Cookie信息失败 ：%s", e.getMessage()));
			throw e;
		} finally {
			page = null;
		}
		return requestId;
	}

	/** ******************************** Tools *********************************************** */

	/** 解析图片价格。 */
	protected String parseImg(Element ele, String type) throws Exception {
		String src = ele.getElementsByTag("img").get(0).attr("src");
		return parseImg(src, type);
	}

	/** 解析图片价格（重载1）。 */
	protected String parseImg(String src, String type) throws Exception {
		if (src.indexOf("time") > -1) src = src.substring(0, src.indexOf("time"));
		src = src.replaceAll("&amp;", "&");
		Thread.sleep(500);
		return imageUtils.WebClient(queryPage, src, type);
	}
}